package com.elock.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.elock.base.core.Filter;
import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.controller.BaseController;
import com.elock.base.core.controller.ResultMsg;
import com.elock.base.core.util.ConvertUtil;
import com.elock.base.core.util.JsonUtils;
import com.elock.entity.SaleOrg;
import com.elock.entity.SystemDict;
import com.elock.entity.TerminalTask;
import com.elock.service.SaleOrgBaseService;
import com.elock.service.SystemDictBaseService;
import com.elock.service.TerminalMessageEventService;
import com.elock.service.TerminalTaskService;

/**
 * Controller - 任务信息
 * 
 * @author 仁德
 */
@Controller("terminalTaskController")
@RequestMapping("/terminal_task")
public class TerminalTaskController extends BaseController {

	@Resource(name = "terminalTaskServiceImpl")
	private TerminalTaskService terminalTaskService;
	@Resource(name = "systemDictBaseServiceImpl")
	private SystemDictBaseService systemDictBaseService;
	@Resource(name = "saleOrgBaseServiceImpl")
	private SaleOrgBaseService saleOrgBaseService;
	@Resource(name = "terminalMessageEventServiceImpl")
	private TerminalMessageEventService terminalMessageEventService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list_tb", method = RequestMethod.GET)
	public String list_tb(ModelMap model) {

		return "/terminal_task/list_tb";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Pageable pageable, ModelMap model) {

		return "/terminal_task/list";
	}

	/**
	 * 列表数据
	 */
	@RequestMapping(value = "/list_data", method = RequestMethod.POST)
	public @ResponseBody ResultMsg list_data(String waybillNo, Long categoryId,
			Long fromSaleOrgId, Long toSaleOrgId, Integer status, Pageable pageable,
			ModelMap model) {

		Object[] args = { waybillNo, categoryId, fromSaleOrgId, status, toSaleOrgId };
		Page<Map<String, Object>> page = terminalTaskService.findPage(pageable, args);

		// List<Map<String, Object>> terminalTasks = page.getContent();
		// if (!terminalTasks.isEmpty()) {
		// String ids = "";
		// for (Map<String, Object> map : terminalTasks) {
		// ids += "," + map.get("id");
		// }
		// ids = ids.substring(1);
		// List<Map<String, Object>> terminalTaskItems = terminalTaskService
		// .findItemsByTaskId(ids);
		// List<Map<String, Object>> items = null;
		// for (Map<String, Object> map : terminalTasks) {
		// items = new ArrayList<Map<String, Object>>();
		// String terminalTaskId = map.get("id").toString();
		// for (Map<String, Object> itemMap : terminalTaskItems) {
		// String taskId = itemMap.get("terminal_task").toString();
		// if (terminalTaskId.equals(taskId)) {
		// items.add(itemMap);
		// }
		// }
		// map.put("terminalTaskItems", items);
		// }
		// }

		String jsonPage = JsonUtils.toJson(page);

		return success(jsonPage);
	}

	/**
	 * 添加
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(ModelMap model) {

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("code", "taskCategory"));
		filters.add(Filter.isNotNull("parent"));
		List<SystemDict> categorys = systemDictBaseService.findList(null, filters, null);
		model.addAttribute("categorys", categorys);

		SaleOrg saleOrg = saleOrgBaseService.getCurrentSaleOrg();
		model.addAttribute("saleOrg", saleOrg);

		return "/terminal_task/add";
	}

	/**
	 * 保存
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public @ResponseBody ResultMsg save(TerminalTask terminalTask, Long fromSaleOrgId,
			Long toSaleOrgId, Long categoryId) {

		String plateNum = terminalTask.getPlateNum();
		Integer berth = terminalTask.getBerth();
		SaleOrg fromSaleOrg = saleOrgBaseService.find(fromSaleOrgId);
		terminalTask.setFromSaleOrg(fromSaleOrg);
		SaleOrg toSaleOrg = saleOrgBaseService.find(toSaleOrgId);
		terminalTask.setToSaleOrg(toSaleOrg);

		if (ConvertUtil.isEmpty(terminalTask)) {
			return error("请填写任务单编号");
		}
		if (categoryId != null) {
			terminalTask.setCategory(systemDictBaseService.find(categoryId));
		}
		String waybillNo = terminalTaskService.findWorkingItem(plateNum,
				berth,
				terminalTask.getId());
		if (!ConvertUtil.isEmpty(waybillNo)) {
			return error("车辆["
					+ plateNum
					+ "]的舱位["
					+ berth
					+ "]已存在于未关闭或未结束的任务单["
					+ waybillNo
					+ "]中");
		}
		terminalTaskService.save(terminalTask);

		return success().addObjX(terminalTask.getId());
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit", method = RequestMethod.GET)
	public String edit(Long id, ModelMap model) {

		TerminalTask terminalTask = terminalTaskService.find(id);
		model.addAttribute("terminalTask", terminalTask);

		// List<Map<String, Object>> terminalTaskItems = terminalTaskService
		// .findItemsByTaskId(terminalTask.getId().toString());
		// model.addAttribute("terminalTaskItems",
		// JsonUtils.toJson(terminalTaskItems));

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("code", "taskCategory"));
		filters.add(Filter.isNotNull("parent"));
		List<SystemDict> categorys = systemDictBaseService.findList(null, filters, null);
		model.addAttribute("categorys", categorys);

		List<Map<String, Object>> terminalMessageEvents = terminalMessageEventService
				.findListByTaskSn(terminalTask.getSn());
		model.addAttribute("terminalMessageEvents",
				JsonUtils.toJson(terminalMessageEvents));

		return "/terminal_task/edit";
	}

	/**
	 * 编辑
	 */
	@RequestMapping(value = "/edit_sn", method = RequestMethod.GET)
	public String edit_sn(String sn, ModelMap model) {

		List<Filter> filters = new ArrayList<Filter>();
		filters.add(Filter.eq("sn", sn));
		TerminalTask terminalTask = terminalTaskService.find(filters);
		model.addAttribute("terminalTask", terminalTask);

		// List<Map<String, Object>> terminalTaskItems = terminalTaskService
		// .findItemsByTaskId(terminalTask.getId().toString());
		// model.addAttribute("terminalTaskItems",
		// JsonUtils.toJson(terminalTaskItems));

		filters.clear();
		filters.add(Filter.eq("code", "taskCategory"));
		filters.add(Filter.isNotNull("parent"));
		List<SystemDict> categorys = systemDictBaseService.findList(null, filters, null);
		model.addAttribute("categorys", categorys);
		List<Map<String, Object>> terminalMessageEvents = terminalMessageEventService
				.findListByTaskSn(sn);
		model.addAttribute("terminalMessageEvents",
				JsonUtils.toJson(terminalMessageEvents));

		return "/terminal_task/edit";
	}

	/**
	 * 更新
	 */
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public @ResponseBody ResultMsg update(TerminalTask terminalTask, Long fromSaleOrgId,
			Long toSaleOrgId, Long categoryId) {

		String plateNum = terminalTask.getPlateNum();
		Integer berth = terminalTask.getBerth();
		SaleOrg saleOrg = saleOrgBaseService.find(fromSaleOrgId);
		terminalTask.setFromSaleOrg(saleOrg);
		SaleOrg toSaleOrg = saleOrgBaseService.find(toSaleOrgId);
		terminalTask.setToSaleOrg(toSaleOrg);
		if (ConvertUtil.isEmpty(terminalTask)) {
			return error("请填写任务单编号");
		}
		if (categoryId != null) {
			terminalTask.setCategory(systemDictBaseService.find(categoryId));
		}

		String waybillNo = terminalTaskService.findWorkingItem(plateNum,
				berth,
				terminalTask.getId());
		if (!ConvertUtil.isEmpty(waybillNo)) {
			return error("车辆["
					+ plateNum
					+ "]的舱位["
					+ berth
					+ "]已存在于未关闭或未结束的任务单["
					+ waybillNo
					+ "]中");
		}
		terminalTaskService.update(terminalTask);

		return success();
	}

	/**
	 * 完成
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/complete", method = RequestMethod.POST)
	public @ResponseBody ResultMsg complete(Long[] ids) {

		if (ids == null || ids.length == 0) {
			return error("请选择需要完成的任务单");
		}
		terminalTaskService.complete(ids);

		return success();
	}

	/**
	 * Excel导入
	 */
	@RequestMapping(value = "/import_excel", method = RequestMethod.POST)
	public @ResponseBody ResultMsg importFromExcel(MultipartFile file) throws Exception {

		terminalTaskService.taskImport(file);
		return ResultMsg.success();
	}

}
